<template>
  <div class="page-dsdata">
    <Tree class="file-tree" ref="fileTree" :data="fileData" :render="fileTreeRender"></Tree>
    <div class="file-table">
      <Input
        v-model.trim="searchName"
        placeholder="请输入名称"
        class="file-table-input"
        search
        @on-search="pageIndex = 1;getDataList('')"
      />
      <strong class="dsdata-select">已选Id：{{selectId}}</strong>
      <Table
        size="small"
        :columns="dataColumns"
        :data="tableData"
        @on-row-click="rowClick"
        :highlight-row="true"
      ></Table>
      <Page
        :total="total"
        size="small"
        v-if="total> 10"
        :current="pageIndex"
        @on-change="changePage"
      />
    </div>

    <div class="file-show" v-if="!hidePreview">
      <div>共{{showtotal}}条数据，预览最多显示20条数据</div>
      <Table size="small" :columns="showColumns" :data="showData" class="ds-show-table" id="dsShowTable"></Table>
    </div>

    <Button class="create-data" type="primary" @click="openCreateData" v-show="currentId !=-1">新建数据集</Button>

    <div class="dsdata-footer">
      <Button @click="cancelHandler" style="margin-right:8px">取消</Button>
      <Button type="primary" @click="okHandler">确定</Button>
    </div>

    <Modal v-model="createDataShow" footer-hide width="500px" title="新建数据集">
      <Form
        ref="createStepForm"
        :model="createStepForm"
        :rules="createStepRules"
        :label-width="120"
      >
        <FormItem label="新建数据集名称：" prop="name">
          <Input
            v-model.trim="createStepForm.name"
            :maxlength="20"
            style="width: 200px;"
            placeholder="请输入"
          ></Input>
        </FormItem>
        <FormItem label="新建数据集标识：" prop="identifier">
          <Input
            v-model.trim="createStepForm.identifier"
            :maxlength="100"
            style="width: 200px;"
            placeholder="请输入"
          ></Input>
        </FormItem>
      </Form>
      <div style="text-align: right">
        <Button @click="createDataShow = false">取消</Button>
        <Button type="primary" @click="createData">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
// import {
//   getDir,
//   getDataSetList,
//   getDataSetData,
//   getProviderList,
//   createDataset
// } from 'http/api/datas';
import { formatDateByStringMatch } from 'assets/scripts/common';
export default {
  props: ['hidePreview', 'fileUrl'],
  data () {
    return {
      fileData: [],
      tableData: [],
      showColumns: [],
      showData: [],
      total: 0,
      searchName: '',
      currentId: '-1',
      createDataShow: false,
      dataColumns: [
        {
          title: '数据集名称',
          key: 'name',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '创建方式',
          key: 'providerName',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '标识',
          key: 'identifier',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '创建时间',
          key: 'createTime',
          render: (h, param) => {
            return (
              <div>
                {formatDateByStringMatch(
                  param.row.createTime,
                  'yyyy-MM-dd'
                )}
              </div>
            );
          }
        }
      ],
      pageIndex: 1,
      selectId: '',
      selectName: '',
      showtotal: 0,
      // 新建数据集
      createStepForm: {
        name: '',
        identifier: '',
        dataProviderId: ''
      },
      createStepRules: {
        name: [
          {
            required: true,
            message: '名称不能为空'
          }
        ],
        identifier: [
          {
            required: true,
            message: '标识不能为空'
          },
          {
            pattern: /^[a-zA-Z]*$/,
            message: '标识只能是英文'
          }
        ]
      }
    };
  },
  methods: {
    // 打开数据集
    openCreateData () {
      if (!this.createStepForm.dataProviderId) {
        // 请求获取自建数据的id
        // getProviderList().then(res => {
        //   if (res && res.providers) {
        //     res.providers.find(item => {
        //       if (item.name === '自建数据') {
        //         this.createStepForm.dataProviderId = item.id;
        //       }
        //     });
        //   }
        // });
      }
      this.createDataShow = true;
      this.$refs.createStepForm.resetFields();
    },

    // 新建数据集
    createData () {
      this.$refs.createStepForm.validate(valid => {
        if (valid) {
          // let { name, identifier, dataProviderId } = this.createStepForm;

          // let obj = {
          //   collectionName: identifier
          // };
          // let param = {
          //   dataProviderId,
          //   name,
          //   identifier,
          //   dataSetDirId: this.currentId,
          //   providerConfig: JSON.stringify(obj)
          // };

          // createDataset(param)
          //   .then(res => {
          //     this.getDataList('新建成功');
          //     this.createDataShow = false;
          //   })
          //   .catch(() => {
          //     this.$Message.error('新建数据集失败');
          //   });
        }
      });
    },

    // 树节点绘制 render 函数
    fileTreeRender (h, { root, node, data }) {
      let bgColor;
      bgColor = data.id === '-1' ? '#d5e8fc' : '#fff';

      return h(
        'span',
        {
          style: {
            display: 'inline-block',
            width: '100%'
          }
        },
        [
          h('span', [
            h('span', {
              class: 'iconfont icon-data-folder',
              style: {
                marginRight: '8px',
                fontSize: '14px',
                color: 'rgba(153,153,153)'
              }
            }),
            h(
              'span',
              {
                style: {
                  fontSize: '14px',
                  color: '#666666',
                  cursor: 'pointer',
                  display: 'inline-block',
                  margin: '0',
                  padding: '0 4px',
                  transition: 'all .2s ease-in-out',
                  backgroundColor: bgColor,
                  borderRadius: '3px',
                  verticalAlign: 'top'
                },
                domProps: {
                  className: 'file-tree-btn',
                  title: data.title,
                  id: `f${data.id}`
                },
                on: {
                  click: e => {
                    // 当前点击的元素dom改变颜色
                    let btns = this.$refs.fileTree.$el.querySelectorAll(
                      '.file-tree-btn'
                    );
                    for (let i = 0; i < btns.length; i++) {
                      btns[i].style.backgroundColor = '#fff';
                    }
                    e.target.style.backgroundColor = '#d5e8fc';
                    this.currentId = data.id;
                    this.getDataList();

                    // 清空预览数据
                    this.showColumns = [];
                    this.showData = [];
                    this.showtotal = 0;
                    document.getElementById('dsShowTable').style.width = 'auto'
                  }
                }
              },
              data.title
            )
          ]),
          h('span', {
            style: {
              display: 'inline-block',
              float: 'right',
              marginRight: '32px'
            }
          })
        ]
      );
    },

    // 改变分页
    changePage (page) {
      this.pageIndex = page;
      this.getDataList();
    },

    // 获取数据集的列表
    getDataList (msg) {
      // getDataSetList({
      //   dataSetDirId: this.currentId || '-1',
      //   name: this.searchName,
      //   pageSize: 10,
      //   pageIndex: this.pageIndex
      // }).then(res => {
      //   if (res) {
      //     this.total = res.total;
      //     this.tableData = res.dataSetDTOs;

      //     if (msg) {
      //       this.$Message.success(msg);
      //     }
      //   }
      // });
    },

    // 行点击
    rowClick (row, index) {
      if (!this.hidePreview) {
        // getDataSetData({
        //   id: row.id,
        //   field: '',
        //   fieldValue: '',
        //   pageIndex: 1,
        //   pageSize: 20
        // }).then(res => {
        //   // showColumns
        //   if (res) {
        //     this.showColumns = [];
        //     let types = {}
        //     res.headers.forEach(item => {
        //       this.showColumns.push({
        //         title: item.name,
        //         key: item.name,
        //         ellipsis: true,
        //         tooltip: true
        //       });

        //       types[item.name] = item.fieldType;
        //     });

        //     // 数据处理下
        //     let newFormData = [];
        //     res.formDatas.forEach(item => {
        //       let item2 = JSON.parse(item);
        //       newFormData.push(item2);
        //     });

        //     if (res.headers.length > 5) {
        //       document.getElementById('dsShowTable').style.width = res.headers.length * 120 + 'px'
        //     } else {
        //       document.getElementById('dsShowTable').style.width = 'auto'
        //     }

        //     newFormData.forEach(item => {
        //       for (let i in item) {
        //         if (types[i] === 'date') {
        //           item[i] = formatDateByStringMatch(item[i], 'yyyy-MM-dd')
        //         }
        //         if (types[i] === 'datetime') {
        //           item[i] = formatDateByStringMatch(item[i])
        //         }
        //       }
        //     })

        //     this.showData = newFormData;
        //     this.showtotal = res.total;

        //     this.selectId = row.id;
        //     this.selectName = row.name;
        //   }
        // });
      } else {
        this.selectId = row.id;
        this.selectName = row.name;
      }
    },

    // 确定
    okHandler () {
      if (!this.selectId) {
        this.$Message.error('请选择数据');
        return;
      }
      this.$emit('okHandler', { id: this.selectId, name: this.selectName });
    },

    // 取消
    cancelHandler () {
      this.$emit('cancelHandler');
    }
  },
  mounted () {
    // getDir().then(res => {
    //   let list = res && res.dirChildren ? res.dirChildren : [];

    //   function dealArr (arr) {
    //     return JSON.parse(
    //       JSON.stringify(arr)
    //         .replace(/name/g, 'title')
    //         .replace(/dirChildren/g, 'children')
    //     );
    //   }

    //   let result = dealArr(list);

    //   this.fileData = [
    //     {
    //       title: '数据管理',
    //       id: '-1',
    //       expand: true,
    //       children: result
    //     }
    //   ];
    // });

    // if (this.fileUrl) {
    //   this.selectId = this.fileUrl;
    // }
  }
};
</script>

<style rel="stylesheet/less" lang="less">
.page-dsdata {
  position: relative;
  max-height: 490px;
  overflow-x: hidden;
  overflow-y: auto;
  .dsdata-footer {
    clear: both;
    text-align: right;
  }
  .file-tree,
  .file-table,
  .file-show {
    float: left;
    width: 200px;
  }
  .file-table {
    width: 400px;
    margin-bottom: 10px;
    .file-table-input {
      width: 240px;
      margin-bottom: 10px;
    }
    .ivu-page {
      margin-top: 10px;
      text-align: center;
    }
    .ivu-table-row {
      cursor: pointer;
    }

    .ivu-table-small td {
      padding: 0;
      height: 30px;
    }
  }
  .file-show {
    width: 550px;
    margin: 52px 0 10px 10px;
    overflow: auto;
    .ivu-table-small td {
      padding: 0;
      height: 30px;
    }
  }
  .file-tree-btn {
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .dsdata-footer {
    margin-top: 10px;
  }
  .dsdata-select {
    line-height: 28px;
    display: block;
  }
  .create-data {
    position: absolute;
    right: 10px;
    top: 0;
  }
}
.ds-show-table {
  .ivu-table-body {
    max-height: 300px;
    overflow-y: auto;
    overflow-x: hidden;
  }
}
</style>
